class DistributedConsensus:
    def __init__(self, theta=0.7):
        self.theta = theta  # Trust threshold
    
    def dynamic_neighbor_selection(self, trust_graph: dict) -> dict:
        """
        Build trusted neighborhood (Algorithm 1 Step 1-3)
        Args:
            trust_graph: {node_i: {node_j: T_ij}}
        Returns:
            Filtered neighborhoods
        """
        neighborhoods = {}
        for node, neighbors in trust_graph.items():
            # Filter neighbors above trust threshold
            neighborhoods[node] = [n for n, t in neighbors.items() if t >= self.theta]
        return neighborhoods
    
    def trust_belief_propagation(self, trust_matrix: np.ndarray, iterations=3):
        """
        Distributed trust consensus (Algorithm 1 Steps 4-10)
        Args:
            trust_matrix: N×N pairwise trust matrix
            iterations: Message passing rounds
        Returns:
            Updated trust matrix
        """
        messages = trust_matrix.copy()  # Initialization
        for _ in range(iterations):
            new_msgs = np.zeros_like(messages)
            for i in range(len(trust_matrix)):
                for j in range(len(trust_matrix)):
                    # Message update rule (Step 8)
                    other_nodes = [k for k in range(len(trust_matrix)) if k != j]
                    product = np.prod([messages[k, i] for k in other_nodes])
                    new_msgs[i, j] = trust_matrix[i, j] * product
            messages = new_msgs
        return messages
